<template>
  <div class="about-master-container">
    <base-breadcrumb :breadcrumb="!isAudit">
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <!-- 编辑时才显示-->
                  <a-form-model-item label="剩余物资处置申请编码">
                    <BaseInput
                      v-model="formData.code"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="项目名称"
                    prop="projectId"
                  >
                    <SelectDownProject
                      v-model="formData.projectId"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="编号"
                    prop="number"
                  >
                    <BaseInput
                      v-model="formData.number"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="金额合计（元）">
                    <BaseInput
                      v-model="formData.sumAmount"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    label="建议处置方式"
                    prop="disposalMethodId"
                  >
                    <a-select
                      v-model="formData.disposalMethodId"
                      :disabled="state === 3"
                    >
                      <a-select-option
                        v-for="item in wayArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                v-if="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="处置明细">
          <a-card
            v-if="activeKey[1]||formData.id"
            slot="description"
            :bordered="false"
          >
            <detail
              :id="formData.id"
              ref="detail"
              :state="state"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM01"
            />
            <div
              v-if="!isAudit"
              class="pub-next-btn"
            >
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div
        v-if="!isAudit"
        class="pub-header-btn page-btn-right-top"
      >
        <template v-if="state !== 3">
          <a-button
            type="primary"
            :loading="loading"
            @click="submit"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="temporaryStorage"
          >
            保存
          </a-button>
        </template>
        <a-button
          v-checkVisibleInDetail
          @click="$close"
        >
          关闭
        </a-button>
      </div>
      <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
  </div>
</template>

<script>
import detail from '../components/detail/detail'
import {
  disposalAdd,
  disposalEdit,
  audit,
  addFile,
  fileList,
  fileDel,
  findListByMainId
} from '@/api/material/remaining/disposal'
import { selectOption } from '@/api/material/goods/goods'
import SelectDownProject from '@/components/Select/SelectDownProject'

export default {
//   name:'a'+Date.now(),
  components: {
    detail,
    SelectDownProject
  },
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    }
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.state = 3
        }
      }
    },
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  data() {
    return {
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      state: Number(this.$route.query.state),
      isSubmit: false,
      formData: {
        createTime: this.getNowTime(),
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        code: '',
        projectId: null,
        projectCode: '',
        number: '',
        sumAmount: '',
        disposalMethodId: null
      },
      isNext: false,
      stepVal: 0,
      addFile: addFile(),
      fileDel: fileDel(),
      fileList: fileList(),
      wayArr: [],
      rules: {
        projectId: { required: true, message: '项目名称不能为空', trigger: 'blur' },
        number: { required: true, message: '编号不能为空', trigger: 'blur' },
        disposalMethodId: { required: true, message: '建议处置方式不能为空', trigger: 'change' }
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted () {
    this.getWay()
    this.$nextTick(() => {
      if (this.state !== 1) {
        this.formData.id = this.$route.query.id
        this.getEditInfo()
        this.isSubmit = true
      }
    })
   //获取通过获取流程配置值
   this.processConfig = await this.$getConfigFn('mm_sur_apply') 
  },
  methods: {
    projectChange: function (val) {
      let _this = this
      _this.project.map(function (item) {
        if (item.code === val) {
          _this.formData.projectCode = val
        }
      })
    },
    getWay: function () {
      let _this = this
      selectOption({
        type: 26
      }).then((res) => {
        if (res.code === 200) {
          _this.wayArr = res.data
          _this.formData.disposalMethodId = res.data[0].id
        }
      })
    },
    stepChange: function (val) {
      if (!this.formData.id && !this.isAudit) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    next: function (val) {
      this.isNext = true
      this.stepVal++
    },
    previous: function () {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    // 获取编辑回显数据
    async getEditInfo() {
      this.loading = true
      let res = await findListByMainId({ id: this.formData.id })
      if (res.code === 200) {
        this.formData = this.$assign(this.formData, res.data)
      }
      this.loading = false
    },
    /**
     * @description: 校验表格
     */
    async checkTable(resolve, reject) {

      let List =
        (await new Promise((resolves, rejects) => {
          this.$refs.detail?.getAll((res) => {
             this.loading = false
            resolves(res.data)
          })
        })) || []
      if (List.length === 0) {
        this.$noticeWarning('处置明细表不能为空！')
        reject()
      }
      for (let index in List) {
        let page = Math.ceil((Number(index) + 1) / this.$refs.detail?.pageSize)
        let row = List[index]
        for (let key in this.$refs.detail?.rules) {
          let value = this.$refs.detail.rules[key]?.[0]
          console.log(value)
          if (this.$isEmpty(row[key])) {
            this.$noticeWarning(`《处置明细表》第${page}页第${Number(index) + 1}行：${value.message}`)
            reject()
            return
          }
        }
      }
      resolve()
    },
    submit() {
      this.setProcessConfig = null;
      if (this.isSubmit) {
        new Promise((resolve, reject) => {
          this.loading = true
          this.checkTable(resolve, reject)
        }).then(() => {
          this.submitApprovalConfirm(this.isSubmit?this.processConfig:6, async(flag)=>{
            if(!flag) {
              this.loading = false
              return
            }
            this.loading = true
            let res = await audit({ baseId: this.formData.id, auditStatus: this.formData.auditStatus })
            this.loading = false
            if (res.code === this.SUCCESS_CODE) {
              this.$message.success('提交成功')
              //提交时，返回id
              this.businessId = this.formData.id;
              this.setProcessConfig = this.processConfig;
              // this.$router.push({ path: '/material/remaining/disposal' })
            }
          })
        })
      } else {
        this.$message.warning('提交之前请先暂存')
      }
    },
    temporaryStorage(isNext) {
      return new Promise((resolve) => {
        if (this.state === 3) {
          this.next()
          resolve(true)
          return
        }
        this.$refs.ruleForm.validate(async (valid, object) => {
          if (valid) {
            this.loading = true
            if (this.state === 2 || this.formData.id) {
              let res = await disposalEdit(this.formData)
              this.loading = false
              if (res.code === this.SUCCESS_CODE) {
                this.$message.success('暂存成功')
                this.isSubmit = true
                if (isNext) {
                  this.next()
                }
                resolve(true)
              }
            } else {
              let res = await disposalAdd(this.formData)
              this.loading = false
              if (res.code === this.SUCCESS_CODE) {
                this.formData.id = res.data.id
                this.$message.success('暂存成功')
                this.isSubmit = true
                await this.getEditInfo()
                if (isNext) {
                  this.next()
                }
                resolve(true)
              }
            }
          } else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
      })
    }
  }
}
</script>
